//
//  ChangePhoneViewController.swift
//  OnceNectar
//
//  Created by Zhang Dream on 2018/6/27.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import DynamicBlurView
import Alamofire
import PKHUD
import YYModel
import SwiftyJSON

class ChangePhoneViewController: BaseViewController {

    @IBOutlet weak var codeButton: UIButton!
    @IBOutlet weak var bindBtn: UIButton!
    @IBOutlet weak var phoneText: UITextField!
    @IBOutlet weak var pswText: UITextField!
    
    var timer: Timer?
    var sendCount: Int = 60
    var isUpdate: Bool = false

    typealias phoneBlock = (_ str: String) -> Void
    var phoneblock: phoneBlock?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "更改手机号"
        self.phoneText.text = (MineInfoModel.share.userInfModel?.mobilePhone)!
        // Do any additional setup after loading the view.
        
    }
    
    override func setNavigation() {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func bindAct(_ sender: Any) {
        if (phoneText.text?.isEmpty)! {
            self.showToast(msg:"手机号码不能为空")
            return
        }
        if !(self.isValidPhone(phone: phoneText.text! as NSString)) {
            self.showToast(msg:"手机号码格式不对")
            return
        }
        if (pswText.text?.isEmpty)! {
            self.showToast(msg:"请输入验证码")
            return
        }
        
        if isUpdate {
            let parameter:[String : String] = ["vcode": pswText.text!,"mp":phoneText.text!]
            Alamofire.request(appendUrl(suffix: updateUserPhoneUrl), method: .get, parameters: parameter, encoding: URLEncoding.default, headers: ["token":MineInfoModel.share.token!]).responseJSON(completionHandler: { (response) in
                if(response.error == nil){
                    let result = response.result.value as? NSDictionary
                    let json = JSON(result)
                    if json["code"].int == 1{
                        let mineInfoModel = MineInfoModel.share
                        mineInfoModel.userInfModel?.mobilePhone = self.phoneText?.text
                        mineInfoModel.saveUserData(userinfo: mineInfoModel.userInfModel?.toDictionary() as! NSMutableDictionary)
                        mineInfoModel.loadUserData()
                        self.phoneblock!((self.phoneText.text)!)
                        self.navigationController?.popViewController(animated: true)
                    }else if json["code"].int == 100{
                        self.showToast(msg:json["message"].string!)
                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                        self.navigationController?.pushViewController(loginVC, animated: true)
                    }
                    else{
                        self.showToast(msg:json["message"].string!)
                    }
                }else{
                    self.showToast(msg:"请求失败")
                }
            })
        }else {
            let parameter:[String : String] = ["mp":phoneText.text!, "vcode": pswText.text!]
            Alamofire.request(appendUrl(suffix: verifyCodeUrl), method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil).responseJSON { [weak self](response) in
                if(response.error == nil){
                    let result = response.result.value as? NSDictionary
                    let json = JSON(result)
                    if json["code"].int == 1{
                        self?.phoneText.text = ""
                        self?.phoneText.isEnabled = true
                        self?.phoneText.placeholder = "请输入新的手机号码"
                        self?.pswText.text = ""
                        self?.isUpdate = true
                        self?.sendCount = 0
                        self?.updateCode()
                    }else if json["code"].int == 100{
                        self?.showToast(msg:json["message"].string!)
                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                        self?.navigationController?.pushViewController(loginVC, animated: true)
                    }
                    else{
                        self?.showToast(msg:json["message"].string!)
                    }
                }else{
                    self?.showToast(msg:"请求失败")
                }
            }
        }
        
    }
    
    @IBAction func codeAct(_ sender: Any) {
        if (phoneText.text?.isEmpty)! {
            self.showToast(msg:"手机号码不能为空")
        }
        if !(self.isValidPhone(phone: phoneText.text! as NSString)) {
            self.showToast(msg:"手机号码格式不对")
            return
        }
        let requesturl = "\(BaseURL)\(getCodeUrl)"
        var isCheck:String = "1"
        if isUpdate {
            isCheck = "0"
        }
        let parameter:[String : String] = ["mp":phoneText.text!, "type": "3", "check" : isCheck]
        self.codeButton.isUserInteractionEnabled = false
        
        Alamofire.request(requesturl, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil).responseJSON { [weak self](response) in
            
            let result = response.result.value as? NSDictionary
            let json = JSON(result!)
            if(response.error == nil){
                
                self?.sendCount = 60
                self?.timer = Timer.scheduledTimer(timeInterval: 1, target: self!, selector: #selector(self?.updateCode), userInfo: nil, repeats: true)
                self?.showToast(msg:json["message"].string!)
                
            }else{
                self?.codeButton.isUserInteractionEnabled = true
                self?.showToast(msg:json["message"].string!)
            }
            
        }
    }
    
    @objc func updateCode() -> Void {
        var enable: Bool = false
        var title: String?
        if self.sendCount > 0 {
            title = "重新发送\(self.sendCount)"
            enable = false
        }else{
            title = "发送验证码"
            enable = true
            if self.timer != nil && (self.timer?.isValid)! {
                self.timer?.invalidate()
            }
            self.timer = nil
            self.sendCount = 60
        }
        self.codeButton.titleLabel?.text = title
        self.codeButton.setTitle(title, for: .normal)
        self.codeButton.isUserInteractionEnabled = enable
        self.sendCount -= 1
    }
    
    
}
